﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Zero.UControl.Component
{
    /// <summary>
    /// BubbleToolBox.xaml 的交互逻辑
    /// </summary>
    public partial class BubbleToolBox : UserControl
    {
        public BubbleToolBox()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Window parentWindow = Window.GetWindow(this);
            PART_Popup.PlacementTarget = parentWindow;
            if (parentWindow != null)
            {
                parentWindow.LocationChanged += (_, _) => RefreshPopup();
                parentWindow.SizeChanged += (_, _) => RefreshPopup();
                parentWindow.StateChanged += (_, _) => RefreshPopup();
            }
        }

        private void RefreshPopup()
        {
            if (PART_Popup != null)
            {
                var offset = PART_Popup.HorizontalOffset;
                PART_Popup.HorizontalOffset = offset + 1;
                PART_Popup.HorizontalOffset = offset;
            }
        }

        private bool showArrow = false;

        public bool ShowArrow
        {
            get { return showArrow; }
            set 
            {
                showArrow = value;
                if (value)
                {
                    PART_Arrow.Visibility = Visibility.Visible;
                }
                else
                {
                    PART_Arrow.Visibility = Visibility.Collapsed;
                }
            }
        }


        /// <summary>
        /// 箭头边距，可动态定位箭头位置（默认 Left=20）。
        /// </summary>
        public Thickness ArrowMargin
        {
            get => (Thickness)GetValue(ArrowMarginProperty);
            set => SetValue(ArrowMarginProperty, value);
        }

        public static readonly DependencyProperty ArrowMarginProperty =
            DependencyProperty.Register(nameof(ArrowMargin), typeof(Thickness), typeof(BubbleToolBox), new PropertyMetadata(new Thickness(20, 0, 0, 0), OnArrowMarginChanged));

        private static void OnArrowMarginChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is BubbleToolBox bt && bt.PART_Arrow != null)
            {
                bt.PART_Arrow.Margin = (Thickness)e.NewValue;
            }
        }
    }
}
